<?php
namespace common\components\behaviors;

use yii;
use yii\base\Behavior;
use yii\db\ActiveRecord;
use common\models\BaseImg;
use yii\web\UploadedFile;
use linslin\yii2\curl\Curl;

class ImageBehavior extends Behavior {
    
	protected $file;
	
    public $fileAttribute = 'img_id';
    
    public $uploadRootDirectory = 'uploads';
    
    public $dateDirectory = true;
    
    public function events() {
        return [
            ActiveRecord::EVENT_BEFORE_INSERT => 'beforeInsert',
            ActiveRecord::EVENT_BEFORE_UPDATE => 'beforeInsert',
        	ActiveRecord::EVENT_AFTER_DELETE => 'afterDelete'
        ];
    }
    
    /**
     * 
     * @Title: beforeInsert
     * @Description: 提交带有图片，出发此事件行为 
     * @return: return_type
     * @author: kai.gao
     * @date: 2014-11-21 上午1:32:33
     */
    public function beforeInsert() {

        $model = $this->owner;
        if ($model->hasAttribute($this->fileAttribute) && isset($_POST['BaseImg'])) {
// 	       	$image = (!$model->isNewRecord && $model->img_id > 0) ? BaseImg::findOne($model->img_id) : new BaseImg();

	       	$image = (!$model->isNewRecord && $model->img_id > 0) ? !is_null(BaseImg::findOne($model->img_id)) ? BaseImg::findOne($model->img_id) : new BaseImg() : new BaseImg();
	       	$this->file = UploadedFile::getInstance($image, 'img_url');

	       	if (is_object($this->file)) {
	       		//f_d($this->file);
	       		$file_size = $this->file->size/1024;
	       		if($file_size>1024){
	       			f_d("图片大小不能超过1024K");
	       		}
	       		$allFileName = Yii::$app->basePath.'/../uploads/'.$this->getFileName();
                               
	       		$this->file->saveAs($allFileName);
	       		//f_d($this->file);
       			$img_url = f_remote_upload($allFileName);
       			//f_d($img_url);
       			$image->img_url = $img_url ? $img_url : substr(f_img($model->img_id),26);
       			if (!$image->save()) {
					f_d($image->getErrors());
	       		} else {
	       			$model->img_id = $image->id;
	       			//f_d($model->img_id);
	       		}
	       	}
        }
    }
    
    /**
     * 
     * @Title: afterDelete
     * @Description: 信息删除后，同时删除图片 
     * @return: return_type
     * @author: kai.gao
     * @date: 2014-11-24 下午7:15:44
     */
    public function afterDelete() {
    	$model = $this->owner;
    	if ($model->hasAttribute($this->fileAttribute)) {
    		if (($image = BaseImg::findOne($model->img_id)) != null) {
    			$image->delete();
    		}
    	}
    }
    
    /**
     *
     * @Title: getImg
     * @Description: 如果该模型有图片img_id属性，直接返回图片地址
     * @return: string
     * @author: kai.gao
     * @date: 2014-11-21 上午10:28:15
     */
    public function getImg() {
    	if ($this->owner->hasAttribute('img_id') && $this->owner->img_id > 0) {
    		return IMAGE_URL.'/'.BaseImg::findOne($this->owner->img_id)->img_url;
    	} else {
    		return IMAGE_URL.'/undefined.jpg';
    	}
    }
    
    public function getImgUrl() {
    	return $this->owner->hasOne(BaseImg::className(), ['id' => 'img_id']);
    }
    
   	/**
    * 
    * @Title: getFileName
    * @Description:  获取图片
    * @return: string
    * @author: kai.gao
    * @date: 2014-11-22 下午12:09:03
    */
    protected function getFileName() {
    	return $this->uuid().'.'.$this->file->getExtension();
    }
    
    /**
     * 
     * @Title: uuid
     * @Description: 生成随机图片名称 
     * @return: string
     * @author: kai.gao
     * @date: 2014-11-22 下午12:08:48
     */
    protected function uuid() {
    	$being_timestamp = 1206576000;
    	$suffix_len = 3;
    	$time = explode(' ', microtime());
    	$id = ($time[1] - $being_timestamp) . sprintf('%06u', substr($time[0], 2, 6));
    	if ($suffix_len > 0) {
    		$id .= substr(sprintf('%010u', mt_rand()), 0, $suffix_len);
    	}
    	return $id;
    }
}